<template>
  <div class="edit_box">
    <el-scrollbar>
      <el-form
        ref="csForm"
        class="csForm"
        :model="pageData.formData"
        :rules="pageData.formRules"
        status-icon
        label-width="120px"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="机工具编号：" prop="fEquipCode">
              <el-input
                v-model="pageData.formData.fEquipCode"
                placeholder="请输入机工具编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机工具名称：" prop="fEquipName">
              <el-input
                v-model="pageData.formData.fEquipName"
                placeholder="请输入机工具名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制造商：" prop="fProductAffiliation">
              <el-select
                v-model="pageData.formData.fProductAffName"
                placeholder="请选择制造商"
                style="width: 100%"
                @visible-change="selectManufacturer"
                @change="selectManufacturerID"
              >
                <el-option
                  v-for="item in pageData.manufacturer"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格：" prop="fProductSpec">
              <el-input
                v-model="pageData.formData.fProductSpec"
                placeholder="请输入规格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类别：" prop="fEcName">
              <el-select
                v-model="pageData.formData.fEcName"
                placeholder="请选择类别"
                style="width: 100%"
                @visible-change="selectzbType"
                @change="selectTypeId"
              >
                <el-option
                  v-for="item in pageData.zbType"
                  :key="item.fId"
                  :label="item.label"
                  :value="item.fEcName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号：" prop="fProductModelName">
              <el-select
                v-model="pageData.formData.fProductModelName"
                placeholder="请选择型号"
                style="width: 100%"
                @visible-change="selectzbModel"
                @change="selectzbModelID"
              >
                <el-option
                  v-for="item in pageData.zbModel"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计量单位：" prop="fProductUnitName">
              <el-select
                v-model="pageData.formData.fProductUnitName"
                placeholder="请选择计量单位"
                style="width: 100%"
                @visible-change="selectUnit"
                @change="selectUnitID"
              >
                <el-option
                  v-for="item in pageData.unit"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出厂日期：" prop="fProductionTime">
              <el-date-picker
                v-model="pageData.formData.fProductionTime"
                type="date"
                placeholder="请选择出厂日期"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="首次装备：" prop="fPFirstEquipTime">
              <el-input
                v-model="pageData.formData.fPFirstEquipTime"
                placeholder="请输入首次装备日期"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="序列号管理：" prop="fPIsSerial">
              <el-switch
                v-model="pageData.formData.fPIsSerial"
                active-value="1"
                inactive-value="-1"
                @change="kaiguan"
              >
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="录入人员：">
              <el-input
                v-model="pageData.formData.fFullName"
                autocomplete="off"
                :disabled="!pageData.isAdd || pageData.isAdd"
                placeholder="自动填充"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入时间：">
              <el-input
                v-model="pageData.formData.fCreatorTime"
                autocomplete="off"
                :disabled="!pageData.isAdd || pageData.isAdd"
                placeholder="自动填充"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input
                v-model="pageData.formData.fRemark"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 子表 -->
        <el-row>
          <el-button type="primary" @click="onHandleEquipAdd">
            <el-icon><Plus /></el-icon>
            <span>新增</span>
          </el-button>
          <el-table
            height="250"
            border
            style="width: 100%; margin: 10px 0"
            :data="pageData.formData.productParams"
          >
            <el-table-column prop="fParamCode" label="参数编号">
              <template #default="{ row }">
                <el-input v-model="row.fParamCode" readonly>
                  <template #suffix>
                    <el-icon
                      style="cursor: pointer"
                      @click="onSelectParam(row)"
                    >
                      <ArrowDown />
                    </el-icon>
                  </template>
                </el-input> </template
            ></el-table-column>
            <el-table-column prop="fParamName" label="参数名称"
              ><template #default="{ row }">
                <el-input v-model="row.fParamName" /> </template
            ></el-table-column>
            <el-table-column prop="fParamValue" label="参数值">
              <template #default="{ row }">
                <el-select
                  v-model="row.fParamValue"
                  style="width: 100%"
                  @visible-change="selectParamsValue(row)"
                  @change="selectParamsValueId(row)"
                  @click="getindex(row)"
                >
                  <el-option
                    v-for="item in pageData.paramValue"
                    :key="item.fDdCode"
                    :label="item.fDdName"
                    :value="item.fDdName"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="fParamValueID" label="参数ID">
              <template #default="{ row }">
                <!-- {{ row }} -->
                <el-input v-model="row.fParamValueID" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="{ row }">
                <el-icon
                  title="删除"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleEquipDel(row)"
                >
                  <Delete />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row>
      <el-col :span="24" style="text-align: right">
        <el-button @click="onHandleCancel">取消</el-button>
        <el-button type="primary" @click="onHandleSure"> 提交 </el-button>
      </el-col>
    </el-row>

    <!-- 选择装备参数 -->
    <el-dialog
      :width="800"
      title="选择机工具参数"
      v-model="pageData.selectParamVisible"
      :close-on-click-modal="false"
      destroy-on-close
      append-to-body
      custom-class="editDialog-class"
    >
      <selectmtrparam
        @ok="onParamCallbackOk"
        @cancel="() => (pageData.selectParamVisible = false)"
      />
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, watch } from "vue";
import { ElLoading, ElMessage,ElMessageBox } from "element-plus";
import { Plus, Delete, ArrowDown } from "@element-plus/icons-vue";
import selectmtrparam from "@/components/select/selectmtrparam.vue";

import {
  add_equip,
  select_equip,
  select_equipModel,
  select_equipDetails,
  update_equip,
  select_Manufacturer,
  select_Model,
  select_UnitList,
} from "@/api/basic/machinetoolinfo";
import { delete_equipParams, query_selectddcode } from "@/api/basic/equipinfo";

export default {
  components: { Plus, Delete, ArrowDown, selectmtrparam },

  props: {
    modifyObj: { type: Object, required: true },
    isAdd: { type: Boolean, required: true, default: false },
  },
  setup(props, context) {
    onMounted(() => {
      pageData.formData = {
        fAuditUserId: "",
        fAuditorTime: "",
        fBookCode: "",
        fCreateUserId: "",
        fCreatorTime: "", //录入时间
        fEcName: "",
        fFullName: "", //录入人员
        fId: "",
        fPFirstEquipTime: "", //首次装备日期
        fPIsSerial: 1, //序列号管理
        fPpInfo: "",
        fEquipCode: "",
        fEquipName: "",
        fLastModifyTime: "",
        fLastModifyUserId: "",
        // fPIsSerial: 1, //序列号管理
        fPcId: "", //类别ID
        fProductAffiliation: "", //所属单位
        fProductCode: "", //装备编号
        fProductModel: "", //型号
        fProductName: "", //装备名称
        fProductPic: "",
        fProductSpec: "", //规格
        fProductCategory: 70,
        fProductSupplier: "",
        fProductUnit: "", //计量单位
        fProductVender: "",
        fProductionTime: "", //出厂日期
        fRemark: "",
        fState: 0,
        fppInfo: "",
        productParams: [] /* 参数信息表 */,
        fDtlId: "", //装备id
      };
    });

    // 表单绑定返回的数据
    const csForm = ref();

    let pageData = reactive({
      // 制造商
      manufacturer: [],
      // 参数值
      paramValue: [],
      fPcAffProduct: 3,
      // 装备类型
      zbType: [],
      // 装备型号
      zbModel: [],
      // 计量单位
      unit: [
        {
          value: "箱",
          label: "箱",
        },
        {
          value: "个",
          label: "个",
        },
        {
          value: "包",
          label: "包",
        },
      ],
      formData: {
        productParams: [],
        fPIsSerial: "1", //序列号管理
      },
      formRules: {
        fEquipCode: [
          { required: true, message: "请输入装备编号", trigger: "blur" },
        ],
        fEquipName: [
          { required: true, message: "请输入装备名称", trigger: "blur" },
        ],
        fProductAffiliation: [
          { required: true, message: "请选择制造商", trigger: "blur" },
        ],
        fProductSpec: [
          { required: true, message: "请输入规格", trigger: "blur" },
        ],
        fProductModelName: [
          { required: true, message: "请选择型号", trigger: "blur" },
        ],
        fProductUnitName: [
          { required: true, message: "请选择计量单位", trigger: "blur" },
        ],
        fEcName: [{ required: true, message: "请选择类别", trigger: "blur" }],
      },

      isAdd: props.isAdd,
      currentRow: {},
      selectParamVisible: false, //选择装备参数弹窗
    });

    // 选择时间开始
    const size = (ref < "default") | "large" | ("small" > "default");
    const shortcuts = [
      {
        text: "Today",
        value: new Date(),
      },
      {
        text: "Yesterday",
        value: () => {
          const date = new Date();
          date.setTime(date.getTime() - 3600 * 1000 * 24);
          return date;
        },
      },
      {
        text: "A week ago",
        value: () => {
          const date = new Date();
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
          return date;
        },
      },
    ];

    const disabledDate = (time) => {
      return time.getTime() > Date.now();
    };
    // 选择时间结束

    /* 增加子表中参数信息 */
    const onHandleEquipAdd = () => {
      const dtl = {
        fAuditUserId: "",
        fAuditorTime: "",
        fBookCode: "",
        fCreateUserId: "",
        fCreatorTime: "",
        fDtlId: "",
        fId: "",
        fLastModifyTime: "",
        fLastModifyUserId: "",
        fParamCode: "",
        fParamName: "",
        fParamSort: 0,
        fParamValue: "",
        fParamValueID: "",
        fRemark: "",
        // fState: 0,
      };
      // console.log(pageData, dtl);
      pageData.formData.productParams.push(dtl);
    };
    // 删除参数
    const onHandleEquipDel = (row) => {
      const index = pageData.formData.productParams.indexOf(row);
      const fId = pageData.formData.productParams[0].fId;
      ElMessageBox.confirm("是否确定删除该参数，删除后不可撤销", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delete_equipParams(fId)
            .then((res) => {
              console.log("删除参数子表res", res);
              ElMessage.success("删除成功");
              if (index > -1) {
                pageData.formData.productParams.splice(index, 1);
              }
            })
            .catch((error) => {
              console.log("删除子表出错", error);
              ElMessage.error("删除失败");
            });
          // if (index > -1) {
          //   pageData.formData.productParams.splice(index, 1);
          // }
        })
        .catch(() => {
          // ElMessage.error(error.message || "请求出错");
          ElMessage.error("删除失败");
        });
      // delete_equipParams(fId)
      //   .then((res) => {
      //     console.log("删除参数子表res", res);
      //   })
      //   .catch((error) => {
      //     console.log("删除子表出错", error);
      //   });
      // if (index > -1) {
      //   pageData.formData.productParams.splice(index, 1);
      // }
    };
    // 选择参数
    const onSelectParam = (obj) => {
      pageData.currentRow = obj;
      pageData.selectParamVisible = true;
    };

    const onParamCallbackOk = (obj) => {
      console.log("父组件", obj);
      pageData.selectParamVisible = false;
      if (obj !== null && obj.length > 0) {
        const obj2 = obj[0].obj;
        console.log("objobj", obj2);
        // pageData.currentRow.fDdName = obj2.fDdName;
        // pageData.currentRow.fDdCode = obj2.fDdCode;
        pageData.currentRow.fParamCode = obj2.fParamCode;
        pageData.currentRow.fParamName = obj2.fParamName;
        pageData.currentRow.fParamValue = obj2.fParamValue;
        pageData.currentRow.fParamValueID = obj2.fParamValueID;
        pageData.currentRow.fParamFromId = obj2.fParamFromId;
        console.log("pageData.currentRow", pageData.currentRow);
      }
    };
    // 选择参数值
    const getindex = (row) => {
      // console.log(row)
      let index = pageData.formData.productParams.indexOf(row);
      console.log("index", index);
      pageData.nowIndex = index;
    };
    const selectParamsValue = (row) => {
      console.log("row", row);
      query_selectddcode(row.fParamCode)
        .then((res) => {
          console.log("选择参数值", res);
          pageData.paramValue = res;
        })
        .catch((error) => {
          console.log("参数信息1", error);
        });
    };
    const selectParamsValueId = (val) => {
      console.log("val", val);
      query_selectddcode(val.fParamCode)
        .then((res) => {
          console.log("选择参数值", res);
          var csdata = res.filter((item, index) => {
            console.log("item", item);
            return item.fDdName == val.fParamValue;
          });
          console.log("csdata", csdata);
          pageData.formData.productParams[pageData.nowIndex].fParamValueID =
            csdata[0].fDdCode;
        })
        .catch((error) => {
          console.log("参数信息报错", error);
        });
    };

    // 选择制造商
    const selectManufacturer = () => {
      select_Manufacturer()
        .then((res) => {
          console.log("制造商1", res);
          pageData.manufacturer = res;
        })
        .catch((error) => {
          console.log("装备类别报错error", error);
        });
    };
    const selectManufacturerID = (val) => {
      console.log("val", val);
      select_Manufacturer()
        .then((res) => {
          console.log("制造商2", res);
          const data = res.filter((item) => {
            return (item.id = val);
          });
          console.log("data", data);
          pageData.formData.fProductAffiliation = data[0].id;
          // console.log(
          //   "pageData.formData.fProductAffiliation",
          //   pageData.formData.fProductAffiliation
          // );
        })
        .catch((error) => {
          console.log("装备类别报错error", error);
        });
    };

    // 选择装备型号
    const selectzbModel = () => {
      select_Model()
        .then((res) => {
          pageData.zbModel = res;
        })
        .catch((error) => {
          console.log("装备型号报错error", error);
        });
    };
    const selectzbModelID = (val) => {
      select_Model()
        .then((res) => {
          const data = res.filter((item) => {
            return (item.id = val);
          });
          console.log("xinghao data", data);
          pageData.formData.fProductModel = data[0].id;

          // pageData.zbModel = res;
        })
        .catch((error) => {
          console.log("装备型号报错error", error);
        });
    };

    // 选择计量单位
    const selectUnit = () => {
      select_UnitList()
        .then((res) => {
          pageData.unit = res;
        })
        .catch((error) => {
          console.log("装备型号报错error", error);
        });
    };
    const selectUnitID = (val) => {
      select_UnitList()
        .then((res) => {
          const data = res.filter((item) => {
            return (item.id = val);
          });
          console.log("xinghao data", data);
          pageData.formData.fProductUnit = data[0].id;
        })
        .catch((error) => {
          console.log("装备型号报错error", error);
        });
    };

    // 选择装备id
    const selectTypeId = (val) => {
      console.log("选择的值", val);
      select_equip(pageData.fPcAffProduct)
        .then((res) => {
          console.log("res1111111", res);
          // 过滤res.data  把选中的数据的值赋给item
          let typedata = res.filter((item, index) => {
            return item.fEcName == val;
          });
          pageData.formData.fPcId = typedata[0].fId;
        })
        .catch(() => {});
    };
    // 选择装备类别
    const selectzbType = () => {
      select_equip(pageData.fPcAffProduct).then((res) => {
        pageData.zbType = res;
      });
    };

    const kaiguan = (val) => {
      console.log("开关val", val);
    };

    const onHandleCancel = () => {
      csForm.value?.resetFields();
      context.emit("cancel");
    };
    // 查询装备详情
    if (!props.isAdd) {
      select_equipDetails(props.modifyObj.fId).then((res) => {
        pageData.formData = res[0];

        console.log("121212", res);
        pageData.formData.fEquipCode = res[0].fProductCode;
        pageData.formData.fEquipName = res[0].fProductName;
        pageData.formData.productParams = res[0].productParams;
        pageData.formData.fPIsSerial = res[0].fPIsSerial.toString();
        // pageData.formData.fParamFromId
        console.log("first", typeof pageData.formData.fPIsSerial);
      });
    }
    // 提交
    const onHandleSure = () => {
      csForm.value?.validate((valid) => {
        if (valid) {
          const loading = ElLoading.service({
            lock: true,
            background: "rgba(0, 0, 0, 0.7)",
          });
          if (props.isAdd) {
            console.log("新增", pageData.formData);
            // 新增
            add_equip(pageData.formData)
              .then((res) => {
                console.log("新增", pageData.formData);
                console.log("返回的数据", res);
                loading.close();
                ElMessage({
                  type: "success",
                  message: "新增成功",
                });
                context.emit("ok", {
                  isAdd: props.isAdd,
                  retObj: pageData.formData,
                });
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          } else {
            pageData.formData.fCreatorTime = new Date(
              pageData.formData.fCreatorTime
            );
            pageData.formData.fProductionTime = new Date(
              pageData.formData.fProductionTime
            );
            pageData.formData.fProductCategory = 70;
            update_equip(pageData.formData)
              .then((res) => {
                console.log("装备编辑", res);
                // if (res == 1) {
                loading.close();
                context.emit("ok", {
                  isAdd: props.isAdd,
                  retObj: pageData.formData,
                });
                ElMessage({
                  type: "success",
                  message: "编辑成功",
                });
                // }

                // window.location.reload();
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          }
        } else return false;
      });
    };

    // const getData = (item) => {
    //   console.log("item", item);
    //   select_equipDetails(item.fId) //查询装备详情
    //     .then((res) => {
    //       console.log("121212", res.data);
    //       pageData.formData = res.data;
    //       // pageData.formData.fEquipCode = res.data.fProductCode;
    //       // pageData.formData.fEquipName = res.data.fProductName;
    //       // pageData.formData.fDtlId = res.data.data.fId;
    //       let fDtlId = res.data.fId;
    //       // console.log("装备id", fDtlId);
    //       query_cstable(fDtlId) //查询参数子表
    //         .then((res) => {
    //           console.log("查询参数子表", res.data);
    //         })
    //         .catch(() => {});
    //     })
    //     .catch((error) => {
    //       ElMessage.error(error.message || "请求出错");
    //     });
    //   // query_cstable()
    //   //   .then(() => {})
    //   //   .catch(() => {});
    // };

    return {
      csForm,
      pageData,
      size,
      shortcuts,
      disabledDate,
      onHandleEquipAdd,
      onHandleEquipDel,
      onSelectParam,
      onParamCallbackOk,
      selectzbType,
      selectzbModel,
      selectzbModelID,
      onHandleCancel,
      onHandleSure,
      kaiguan,
      selectTypeId,
      selectParamsValue,
      selectParamsValueId,
      getindex,
      selectManufacturer,
      selectManufacturerID,
      selectUnit,
      selectUnitID,
    };
  },
};
</script>

<style lang="scss">
.edit_box {
  height: 100%;
  background-color: white;
  .csForm {
    width: calc(100% - 6px);
  }
}
</style>
